(function ($) {
  Drupal.behaviors.message = {
    attach: function (context, settings) {
      let _this = this;
      let enable = false;
      // let enable = Drupal.settings.gateway_client.enable;
      // let socket = Drupal.settings.gateway_client.socket;
      // let token = Drupal.settings.gateway_client.token;
      fly.config.baseURL = "/services/admin";
      fly.interceptors.request.use(function (config, promise) {
        config.headers["X-CSRF-TOKEN"] = token;
      });
      this.socket = false;
      this.on("init", function (client_id) {
        fly.post("/gateway_client/bind_uid", {client_id});
      });
      this.on("commands", function (commands) {
        for (var i in commands) {
          if (commands.hasOwnProperty(i) && commands[i]["command"] && _this[commands[i]["command"]]) {
            _this[commands[i]["command"]](this, commands[i]["data"], 200);
          }
        }
      });
      if (enable) {
        this.start();
      }
    },
    Notify(message, position, timeout, theme, icon, closable) {
      toastr.options.positionClass = "toast-" + position;
      toastr.options.extendedTimeOut = 0; //1000;
      toastr.options.timeOut = timeout;
      toastr.options.closeButton = closable;
      toastr.options.iconClass = icon + " toast-" + theme;
      toastr["custom"](message);
    },
    socket: "",
    socketOpen: false,
    messages: [],
    socketTask: null,
    start() {
      let _this = this;
      this.connect();
      setInterval(function () {
        if (_this.socketTask.readyState === 1) {
          _this.send("ping", Date.now());
        }
        else {
          _this.connect();
        }
      }, 3000);
    },
    connect() {
      console.log(this.socketOpen);
      let _this = this;
      if (!this.socketOpen) {
        this.socketTask = new WebSocket(this.socket);
        this.socketTask.onopen = function (res) {
          _this.socketOpen = true;
          _this.messages.forEach(function (value) {
            let data = JSON.parse(value);
            _this.send(data.type, data.data);
          });
          _this.messages = [];
        };
        this.socketTask.onmessage = function (res) {
          //解析数据
          let data = JSON.parse(res.data);
          //判断是否是函数
          if (_this.isFunction(_this.socketCallback[data.type])) {
            //执行 回调
            _this.socketCallback[data.type](data.data);
          }
        };
      }
    },
    socketCallback: [],
    isFunction: function (obj) {
      return typeof obj === "function" && typeof obj.nodeType !== "number";
    },
    send(type, data) {
      let sData = {
        type: type,
        data: data,
      };
      let json = JSON.stringify(sData);
      if (this.socketOpen) {
        this.socketTask.send(json);
      }
      else {
        this.messages.push(json);
      }
    },
    on(type, func) {
      let _this = this;
      _this.socketCallback[type] = func;
    },
    messageNotify(ajax, response, status) {
      let r = response;
      Drupal.behaviors.message.Notify(r.message, r.position, r.timeout, r.theme, r.icon, r.closable);
    },
    setBadge(ajax, response, status) {
      let mlid = response.mlid;
      mlid = `#${mlid}`;
      let badge = parseInt(response.badge);
      if (badge > 0) {
        $(mlid).html(badge).show();
      }
      else {
        $(mlid).html(badge).hide();
      }
    },
  };
})(jQuery);
